/**
* Created by wangshuyi on 7/6/2017, 2:07:57 PM.
*/

'use strict';

const extend = require('extend');
const logger = require('log4js').getLogger("sys");

const CommonService = require("../../service/util/dbService");
const Model = require("../../module/test/TestModel");

const defaultParams = {
    model : Model
};

class ModuleService extends CommonService{
    constructor(param){
        super(param);
        this.opts = extend(true, {}, this.opts, defaultParams, param);
        this._name = "TestService";
    }
    tree(parentId = '', condition = {}){
        const thisService = this,
        superFind = super.find;
        let total = 1, count = 0, data = {_id: parentId}, _level = 0;

        return new Promise(function (resolve, reject) {
            function callback() {
            count++;
                if(count == total){
                    resolve({level: _level, rows:data.children});
                }
            }

            function find(parent, level) {
                superFind.call(thisService, extend({parent: parent._id}, condition), 'parent', {'sort':1}).then(function (result) {
                    total += result.length;
                    if(result.length > 0){
                        _level = Math.max(level, _level);
                        if(parent._doc){
                            parent._doc.children = result;
                        }else{
                            parent.children = result;
                        }
                        result.forEach(function (subject) {
                            find(subject, level+1);
                        });
                    }

                    callback();
                });
            }

            find(data, 1);
        });
    }
    save(data){
        if(data.parent){
            return new Promise((resolve, reject) => {
                super.updateById(data.parent, {__type:'folder'}).then(result => {
                    super.save(data).then(r => resolve(r), e => reject(e));
                })
            });
        }else{
            return super.save(data);
        }
    }
    removeById(id){
        return new Promise((resolve, reject) => {
            super.removeById(id).then(data => {
                if(data && data.parent){
                    super.find({parent:data.parent}).then(hasChildren => {
                        if(hasChildren.length == 0){
                            super.updateById(data.parent, {__type:'leaf'}).then(result => {
                                resolve(data);
                            }, err => reject(err))
                        }
                    }, err => reject(err))
                }else{
                    resolve(data);
                }
            }, err => reject(err))
        });
    }
}

module.exports = new ModuleService();


